<?php
namespace Helper\Controller;

use Common\Controller\ApiController;
use Util\Tree;

class DistrictController extends ApiController
{

    public function getDistricts()
    {
        $districts = S('pks_districts');
        if (empty($districts)) {
            $ret = M('District')->select();
            $tree = new Tree();
            $tree->load($ret);
            $districts = $tree->deepTree();
            $districts = transform('District', 'listview', $districts);
            S('pks_districts', $districts);
        }

        foreach ($districts as $province) {
        }
        // echo json_encode($districts);
        // dump($districts);
        $this->response($districts);
    }

    public  function getDistrictGroups()
    {
        S('pks_districts_groups', null);
        $districtDict = S('pks_districts_groups');
        if (empty($districts)) {
            $ret = M('District')->select();
            $tree = new Tree();
            $tree->load($ret);
            $districts = $tree->deepTree();
            $districts = transform('District', 'listview', $districts);
            $districtDict = [];
            $districtDict['provinces'] = $districts;
            foreach ($districts as $province) {
                $districtDict['cities'][] = $province['children'] ?: [];
                foreach ($province['children'] as $key => $city) {
                    $districtDict['districts'][$key][] = $city['children'] ?: [];
                }
            }
            foreach ($districtDict['provinces'] as &$province) {
                if (isset($province['children'])) unset($province['children']);
            }
            foreach ($districtDict['cities'] as &$cityGroup) {
                foreach ($cityGroup as &$city) {
                    if (isset($city['children'])) unset($city['children']);
                }
            }
            S('pks_districts_groups', $districtDict);
        }
        $this->response($districtDict);
    }

    public function location()
    {
        $lat = I('get.lat');
        $lng = I('get.lng');
        
    }

}
